package com.bawei.module_mine.viewmodel

import androidx.lifecycle.viewModelScope
import com.bawei.lib_common.mvi.base.BaseViewModel
import com.bawei.module_mine.intent.AddressIntent
import com.bawei.module_mine.model.service.AddressService
import com.bawei.module_mine.state.AddressState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

class AddressViewModel : BaseViewModel<AddressIntent>() {
    private val service by lazy { AddressService() }
    private val _state = MutableStateFlow<AddressState>(AddressState.Init)
    val state: StateFlow<AddressState> get() = _state

    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect { intent ->
                when (intent) {
                    is AddressIntent.GetAddressList -> getAddressList()
                }
            }
        }
    }

    private fun getAddressList() {
        _state.value = AddressState.Loading
        viewModelScope.launch {
            try {
                val response = service.getAddressList()
                if (response.code == 200 && response.data != null) {
                    _state.value = AddressState.Success(response.data)
                } else {
                    _state.value = AddressState.Failed(response.msg ?: "未知错误")
                }
            } catch (e: Exception) {
                _state.value = AddressState.Failed(e.message ?: "网络异常")
            }
        }
    }
} 